<template>
  <div class="rain-game">
    <header class="game-header glass">
      <el-button @click="$router.back()" text><el-icon><ArrowLeft /></el-icon>返回</el-button>
      <div class="score-board">
        <span>得分: {{ score }}</span>
        <span>正确: {{ correctCount }}</span>
        <span>生命: ❤️ × {{ lives }}</span>
      </div>
    </header>

    <div class="game-area" v-if="!gameOver">
      <div 
        v-for="word in fallingWords" 
        :key="word.id"
        class="falling-word glass"
        :style="{ top: word.y + 'px', left: word.x + 'px' }"
      >
        {{ word.word }}
      </div>
      
      <div class="input-area">
        <el-input 
          v-model="inputValue"
          size="large"
          placeholder="快速输入单词..."
          @keyup.enter="checkInput"
          autofocus
        />
      </div>
    </div>

    <div class="game-over glass" v-else>
      <h2>游戏结束！</h2>
      <p>得分: {{ score }}</p>
      <p>正确: {{ correctCount }}</p>
      <el-button type="primary" size="large" @click="restart">再玩一次</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { gameApi } from '@/api/game'

const emit = defineEmits(['finish'])

interface FallingWord {
  id: number
  word: string
  x: number
  y: number
  speed: number
}

const fallingWords = ref<FallingWord[]>([])
const inputValue = ref('')
const score = ref(0)
const correctCount = ref(0)
const lives = ref(3)
const gameOver = ref(false)
const words = ref<any[]>([])
let wordId = 0
let gameLoop: any = null
let spawnTimer: any = null

const loadWords = async () => {
  try {
    const route = useRoute()
    const difficulty = route.query.difficulty || 'hard'
    
    const res = await gameApi.getRandomWords({ count: 20, difficulty: difficulty as string })
    if (res.success && res.data) {
      words.value = res.data
    }
  } catch (error) {
    console.error('加载单词失败:', error)
    ElMessage.error('加载单词失败')
  }
}

const spawnWord = () => {
  if (words.value.length === 0 || gameOver.value) return
  
  const randomWord = words.value[Math.floor(Math.random() * words.value.length)]
  fallingWords.value.push({
    id: wordId++,
    word: randomWord.word,
    x: Math.random() * (window.innerWidth - 150),
    y: -50,
    speed: 1 + Math.random()
  })
}

const updateGame = () => {
  if (gameOver.value) return
  
  fallingWords.value = fallingWords.value.filter(word => {
    word.y += word.speed
    
    if (word.y > window.innerHeight) {
      lives.value--
      if (lives.value <= 0) {
        finishGame()
      }
      return false
    }
    return true
  })
}

const checkInput = () => {
  const input = inputValue.value.trim().toLowerCase()
  if (!input) return
  
  const matchIndex = fallingWords.value.findIndex(w => w.word.toLowerCase() === input)
  
  if (matchIndex !== -1) {
    fallingWords.value.splice(matchIndex, 1)
    score.value += 10
    correctCount.value++
    ElMessage.success('+10分')
  }
  
  inputValue.value = ''
}

const finishGame = () => {
  gameOver.value = true
  if (gameLoop) clearInterval(gameLoop)
  if (spawnTimer) clearInterval(spawnTimer)
  emit('finish', score.value, correctCount.value)
}

const restart = () => {
  score.value = 0
  correctCount.value = 0
  lives.value = 3
  gameOver.value = false
  fallingWords.value = []
  inputValue.value = ''
  loadWords()
  startGame()
}

const startGame = () => {
  gameLoop = setInterval(updateGame, 50)
  spawnTimer = setInterval(spawnWord, 2000)
}

onMounted(() => {
  loadWords()
  startGame()
})

onUnmounted(() => {
  if (gameLoop) clearInterval(gameLoop)
  if (spawnTimer) clearInterval(spawnTimer)
})
</script>

<style scoped lang="scss">
.rain-game {
  width: 100%;
  height: 100vh;
  position: relative;
  overflow: hidden;
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  position: relative;
  z-index: 10;
  
  .score-board {
    display: flex;
    gap: 30px;
    color: white;
    font-size: 1.2rem;
    font-weight: bold;
  }
}

.game-area {
  width: 100%;
  height: calc(100vh - 100px);
  position: relative;
}

.falling-word {
  position: absolute;
  padding: 15px 25px;
  font-size: 1.5rem;
  font-weight: bold;
  color: white;
  border-radius: 10px;
  animation: glow 1s ease-in-out infinite alternate;
}

@keyframes glow {
  from {
    box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
  }
  to {
    box-shadow: 0 0 20px rgba(102, 126, 234, 0.9);
  }
}

.input-area {
  position: fixed;
  bottom: 40px;
  left: 50%;
  transform: translateX(-50%);
  width: 400px;
  max-width: 90%;
  z-index: 100;
}

.game-over {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 60px;
  text-align: center;
  
  h2 {
    color: white;
    font-size: 2.5rem;
    margin-bottom: 30px;
  }
  
  p {
    color: rgba(255, 255, 255, 0.9);
    font-size: 1.3rem;
    margin: 15px 0;
  }
}
</style>

